import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Form, Input, message } from 'antd'
import imgLogo from '@/common/images/logo2.png'
import { UserOutlined, LockOutlined, KeyOutlined } from '@ant-design/icons'
import './register.styl'

export default function Register() {
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()
  const [form] = Form.useForm()

  const onFinish = async (values) => {
    setLoading(true)
    try {
      // 发送注册请求到后端
      const response = await fetch('http://localhost:8080/api/auth/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
          'Accept': '*/*',
          'Host': 'localhost:8080',
        },
        body: JSON.stringify({
          username: values.username,
          password: values.password,
          invitationCode: values.inviteCode // 字段名映射
        })
      })

      const result = await response.json()

      if (result.code === 200) {
        message.success(result.message || '注册成功！')
        navigate('/login') // 注册成功后跳转登录页
      } else {
        // 显示后端返回的错误消息
        message.error(result.message || '注册失败，请重试')
      }
    } catch (error) {
      console.error('注册请求失败:', error)
      message.error('网络错误，请检查连接')
    } finally {
      setLoading(false)
    }
  }

  return (
      <div className="P-register">
        <img src={imgLogo} alt="" className="logo" />
        <div className="register-card">
          <div className="ipt-con">
            <Form form={form} onFinish={onFinish}>
              <Form.Item
                  name="username"
                  rules={[
                    { required: true, message: '请输入用户名' },
                    { min: 3, message: '用户名至少3个字符' }
                  ]}
              >
                <Input prefix={<UserOutlined />} placeholder="用户名" />
              </Form.Item>

              <Form.Item
                  name="password"
                  rules={[
                    { required: true, message: '请输入密码' },
                    { min: 6, message: '密码至少6个字符' }
                  ]}
              >
                <Input.Password prefix={<LockOutlined />} placeholder="密码" />
              </Form.Item>

              {/* 修改了邀请码输入框：移除了格式限制 */}
              <Form.Item
                  name="inviteCode"
                  rules={[
                    { required: true, message: '请输入邀请码' }
                  ]}
              >
                <Input prefix={<KeyOutlined />} placeholder="邀请码" />
              </Form.Item>

              <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  block
              >
                立即注册
              </Button>

              <div className="action-links">
                <Button type="link" onClick={() => navigate('/login')}>
                  已有账号？立即登录
                </Button>
              </div>
            </Form>
          </div>
        </div>
      </div>
  )
}